﻿// ********************************************************************
//  文件名: MyLiteNet.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-3-18
// 
//  修改历史:
// ********************************************************************

using LiteNetLib;
using LiteNetLib.Utils;

namespace MyApp;

public class MyLiteNet
{
    public static void Start()
    {
        EventBasedNetListener listener = new EventBasedNetListener();
        NetManager server = new NetManager(listener);
        server.Start(6324 /* port */);

        listener.ConnectionRequestEvent += request =>
        {
            if(server.ConnectedPeersCount < 10 /* max connections */)
                request.AcceptIfKey("SomeConnectionKey");
            else
                request.Reject();
        };

        listener.PeerConnectedEvent += peer =>
        {
            Console.WriteLine("We got connection: {0}", peer);  // Show peer ip
            NetDataWriter writer = new NetDataWriter();         // Create writer class
            writer.Put("Hello client!");                        // Put some string
            peer.Send(writer, DeliveryMethod.ReliableOrdered);  // Send with reliability
        };

        while (!Console.KeyAvailable)
        {
            server.PollEvents();
            Thread.Sleep(15);
        }
        server.Stop();
    }
}